<template>
	<hx-navbar title="确认订单"></hx-navbar>
	<view class="order-confirm-container" v-if="!loading">
		<!-- 配送方式 -->
		<view class="order-confirm-header">
			<u-radio-group v-model="state.deliveryWay" @change="deliveryWayChange">
				<u-radio name="1">普通快递</u-radio>
				<u-radio name="2">上门自提</u-radio>
			</u-radio-group>
			<u-cell-group :border="false" v-if="state.deliveryWay == '1'" class="user-address">
				<u-cell-item
					icon="map"
					:title-style="titleStyle"
					:border-bottom="false"
					:title="selectedAddress ? selectedAddress.detailAddress : '请选择收货地址'"
					:label="selectedAddress ? selectedAddress.addresseeName + '  ' + selectedAddress.telephone : ''"
					@click="toAddress"
				></u-cell-item>
			</u-cell-group>
		</view>
		<!-- 订单商品内容 -->
		<view class="order-confirm-content">
			<view class="order-confirm-warp" v-for="(goods, goodsIndex) in state.orderInfo.orderItemList" :key="goodsIndex">
				<image :src="goods.picUrl" />
				<view class="right">
					<view class="goods-title"> {{ goods.spuName }} </view>
					<view class="goods-spec"> {{ goods.specsInfo }}</view>
					<view class="goods-price">
						<view class="text-price" style="color: red"> {{ goods.salesPrice }} </view>
						<view class="goods-quantity">x{{ goods.buyQuantity }} </view>
					</view>
				</view>
			</view>
		</view>
		<view class="order-confirm-settlement u-padding-top-20">
			<view class="order-confirm-settlement-warp">
				<view class="item">
					<view class="title u-padding-bottom-18"> 价格明细 </view>
				</view>
				<view class="item">
					<view class="title"> 商品总额 </view>
					<view class="text-price price"> {{ state.orderInfo.totalPrice }} </view>
				</view>
				<view class="item">
					<view class="title"> 应付运费 </view>
					<view class="text-price price"> {{ state.orderInfo.freightPrice }} </view>
				</view>
				<view class="item">
					<view class="title"> 店铺优惠券 </view>
					<view style="color: red" v-if="state.orderInfo.couponUserId" @click="showCoupon(state.orderInfo)">
						<text>- </text>
						<text class="text-price price"> {{ state.orderInfo.couponPrice }} </text> <u-icon name="arrow-right" size="26"></u-icon>
					</view>
					<view
						@click="showCoupon(state.orderInfo)"
						v-if="state.orderInfo.couponUserList && state.orderInfo.couponUserList.length > 0 && !state.orderInfo.couponUserId"
					>
						选择优惠券 <u-icon name="arrow-right" size="26"></u-icon>
					</view>
					<view v-if="state.orderInfo.couponUserList.length <= 0 && !state.orderInfo.couponUserId" class="u-font-12"> 无可用优惠券 </view>
				</view>
				<view class="total-price"
					><text style="font-size: 24rpx; color: #909090" class="u-padding-right-10"></text> 合计：<text class="text-price price">{{
						state.orderInfo.paymentPrice
					}}</text>
				</view>
			</view>
		</view>
		<u-gap height="150"></u-gap>
		<!-- 底部导航 -->
		<view class="order-confirm-navigation">
			<view class="order-confirm-navigation-warp">
				<view class="left">
					<view class="text-price text"> {{ state.orderInfo.paymentPrice }} </view>
				</view>
				<view class="right"><u-button type="error" size="medium" shape="circle" @click="toPay">立即支付</u-button> </view>
			</view>
		</view>
		<!-- 领券弹窗 -->
		<u-popup v-model="couponState.couponPopup" mode="bottom" :safe-area-inset-bottom="true" :border-radius="20" :closeable="true" height="500px">
			<view style="margin-top: 40px">
				<CouponConfirm
					:checkedCouponId="couponState.couponUserId"
					:list="couponState.couponUserList"
					:price="couponState.orderPrice"
					@confirm="couponConfirm"
				></CouponConfirm>
			</view>
			<u-gap height="200"></u-gap>
			<view class="confirm-btn">
				<u-button type="primary" @click="onCouponConfirm">确认</u-button>
			</view>
		</u-popup>
	</view>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { useGoodsStore } from '@/stores/goods';
import { getDefault } from '@/api/user/address';
import { getPage as getCouponList } from '@/api/promotion/couponUser';
import { orderCreate, orderSettlement } from '@/api/order/orderInfo';
import CouponConfirm from '@/components/coupon-confirm/index.vue';
import { storeToRefs } from 'pinia';
interface State {
	orderInfo: Array<any>;
	orderItemList: Array<any>;
	totalPrice: number;
	freightPrice: number;
	couponPrice: number;
	vipPrice: number;
	paymentPrice: number;
	deliveryWay: string;
	createWay: string;
}
interface CouponState {
	couponUserList: Array<any>;
	orderPrice: number;
	couponPopup: boolean;
	currentShopId: string;
	couponUserId: string;
}
interface Address {
	id: string;
	detailAddress: string;
	addresseeName: string;
	telephone: string;
}
const titleStyle = ref({
	fontWeight: '700',
});
const storesGoodsStore = useGoodsStore();
const { goodsList }: Partial<any> = storeToRefs(storesGoodsStore);
const loading = ref(false);
const selectedAddress = ref<Address>({
	id: '',
	detailAddress: '',
	addresseeName: '',
	telephone: '',
});

const couponState = reactive<CouponState>({
	couponUserList: [],
	orderPrice: 0,
	couponPopup: false,
	currentShopId: '',
	couponUserId: '',
});
const state = reactive<State>({
	orderInfo: [], // 订单
	orderItemList: [], // 结算和下单参数
	totalPrice: 0, // 订单总金额
	freightPrice: 0, // 运费总金额
	couponPrice: 0, // 优惠券减免总金额
	vipPrice: 0,
	paymentPrice: 0, // 支付总金额
	deliveryWay: '1', //配送方式：1.普通快递；2.上门自提；
	createWay: '2', //订单创建方式：1.购物车下单；2.普通购买下单
});
onLoad((options) => {
	state.createWay = options?.createWay;
	initData();
	getDefaultAddress();
});
// 初始化订单
const initData = () => {
	loading.value = true;
	const orderItemList: Array<any> = [];
	goodsList.value.forEach((item) => {
		orderItemList.push({
			spuId: item.spuId,
			picUrl: item.picUrl,
			spuName: item.spuName,
			quantity: item.quantity,
			specsInfo: item.specsInfo,
			skuId: item.skuId,
		});
	});
	state.orderItemList = orderItemList;
	toSettlement();
};
/**
 * 查询默认地址
 */
const getDefaultAddress = () => {
	getDefault().then((res) => {
		selectedAddress.value = res.data;
	});
};
const showCoupon = (item: any) => {
	if (item.couponUserId) {
		couponState.couponUserId = item.couponUserId;
	}
	couponState.couponPopup = true;
	couponState.couponUserList = item.couponUserList;
	couponState.orderPrice = item.totalPrice;
};
// 选中优惠券回调
const couponConfirm = (couponUserId: string) => {
	console.log(couponUserId);
	if (!couponUserId) {
		return;
	}
	couponState.couponUserId = couponUserId
};
const onCouponConfirm = () => {
	couponState.couponPopup = false;
	couponState.couponUserList = [];
	couponState.orderPrice = 0;
	couponState.currentShopId = '';
	toSettlement();
};
// 配送方式切换
const deliveryWayChange = () => {
	toSettlement();
};
// 去结算
const toSettlement = () => {
	const orderReqParams = {
		deliveryWay: state.deliveryWay,
		orderType: '1', // 普通订单
		couponUserId: couponState.couponUserId,
		createWay: state.createWay,
		skuReqList: state.orderItemList,
	};
	// 结算订单
	orderSettlement(orderReqParams).then((response) => {
		state.orderInfo = response.data;
		loading.value = false;
	});
};
// 去支付
const toPay = () => {
	const order = {
		deliveryWay: state.deliveryWay,
		userAddressId: '',
		orderType: '1', // 普通订单
		skuReqList: state.orderItemList,
		couponUserId: couponState.couponUserId,
		createWay: state.createWay
	};
	if (state.deliveryWay == '1') {
		if (!selectedAddress.value) {
			return uni.$u.toast('请选择收货地址');
		}
		order.userAddressId = selectedAddress.value.id;
	}
	// 创建订单
	console.log(order)
	orderCreate(order).then((response) => {
		const order = response.data;
		uni.$hxRouter.push({
				type: 'redirectTo',
				url: 'pages/order/order-pay/index?id=' + order.id,
			});
	});
};
// 跳转到收货地址页面
const toAddress = () => {
	uni.$hxRouter.push('pages/user/address/index?placeChooseFlag=true');
};
// 监听页面返回事件，并接收参数
uni.$on('update:selectedAddress', (newAddress) => {
	selectedAddress.value = newAddress;
});

// 在页面卸载时移除事件监听
uni.$once('beforeUnload', () => {
	uni.$off('update:selectedAddress');
});
</script>

<style lang="scss">
.confirm-btn {
	position: fixed;
	bottom: 0px;
	width: 100%;
	border: solid 2rpx #f2f2f2;
	background-color: #ffffff;
	padding: 16rpx 0;
	padding-bottom: calc(env(safe-area-inset-bottom) / 2);
	z-index: 99;
}
.order-confirm-container {
	padding: 20rpx;

	.u-cell {
		padding: 0rpx !important;
	}

	.order-confirm-header {
		background-color: #fff;
		padding: 20rpx;
		border-radius: 10rpx;

		.user-address {
			margin-top: 20rpx;
		}
	}

	.order-confirm-content {
		.order-confirm-warp {
			background-color: #fff;
			padding: 20rpx;
			display: flex;

			image {
				width: 160rpx;
				flex: 0 0 160rpx;
				height: 160rpx;
				border-radius: 8rpx;
			}

			.right {
				flex: 1 0 0%;
				height: 100%;
				margin-left: 20rpx;
				display: flex;
				flex-direction: column;
				overflow: hidden;

				.goods-title {
					font-size: 28rpx;
				}

				.goods-spec {
					padding-top: 10rpx;
					font-size: 24rpx;
					color: #909090;
				}

				.goods-price {
					padding-top: 10rpx;
					display: flex;
					justify-content: space-between;
					align-items: center;
				}
			}
		}
	}

	.order-confirm-settlement {
		.order-confirm-settlement-warp {
			background-color: #fff;
			padding: 20rpx;

			.item {
				display: flex;
				align-items: center;
				padding-bottom: 20rpx;
				justify-content: space-between;

				.title {
					font-size: 15px;
				}

				.price {
					font-weight: 700;
					font-size: 15px;
				}
			}

			.total-price {
				display: flex;
				align-items: center;
				padding-bottom: 20rpx;
				justify-content: flex-end;

				.price {
					font-weight: 700;
					color: red;
				}
			}
		}
	}

	.order-confirm-navigation {
		position: fixed;
		bottom: 0px;
		left: 0px;
		display: flex;
		margin-top: 100rpx;
		border: solid 2rpx #f2f2f2;
		background-color: #ffffff;
		padding: 16rpx;
		padding-bottom: calc(env(safe-area-inset-bottom) / 2);
		width: 100%;

		&-warp {
			flex: 1;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding-right: 10rpx;

			.left {
				.text {
					color: red;
					font-size: 38rpx;
				}
			}
		}
	}
}
</style>
